<template>
  <el-card shadow="always">
    <el-form :model="user" ref="form" @submit.native.prevent="submit">
      <el-form-item label="用户名" prop="userName" required>
        <el-input v-model="user.userName" />
      </el-form-item>
      <el-form-item label="密码" prop="password" required>
        <el-input type="password" v-model="user.password" />
      </el-form-item>
      <el-form-item label="电话" prop="phone" required>
        <el-input v-model="user.phone" />
      </el-form-item>
      <el-form-item label="邮箱" prop="email" required>
        <el-input v-model="user.email" />
      </el-form-item>
      <el-form-item label="角色" prop="roleId" required>
        <el-select v-model="user.roleId">
          <el-option label="超级管理员" :value="0" />
          <el-option label="管理员" :value="1" />
          <el-option label="创作者" :value="2" />
          <el-option label="用户" :value="3" />
        </el-select>
      </el-form-item>
      
      <el-alert v-if="alertMessage" :title="alertMessage" type="success" show-icon></el-alert>
      
      <el-form-item>
        <div class="button-container">
          <el-button type="primary" @click="submit">添加</el-button>
          <el-button @click="$emit('close')">取消</el-button>
        </div>
      </el-form-item>
    </el-form>
  </el-card>
</template>

<script>
import axios from '../../axios/axios';

export default {
  props: {
    user: {
      type: Object,
      default: () => ({
        id: 0,
        userName: "",
        password: "",
        phone: "",
        roleId: 0,
        email: "",
      }),
    },
  },
  data() {
    return {
      alertMessage: '', // 提示信息
    };
  },
  methods: {
async submit() {
  try {
    const data = await axios.post('/admin/user/add', this.user); // 直接获取返回的数据
    console.log('响应数据:', data); // 打印获取的数据

    if (data === true) { 
      this.$emit('submit', this.user);
      this.alertMessage = '用户添加成功';
      this.$nextTick(() => {
          this.$message.success(this.alertMessage); // 显示成功消息
      });
    } else {
      this.alertMessage = '添加用户失败'; 
      this.$message.error(this.alertMessage);
    }
  } catch (error) {
    console.error('请求错误', error); // 打印错误信息
    this.alertMessage = '请求失败，请重试'; // 设置请求失败提示
    this.$message.error(this.alertMessage);
  }
},


  },
};
</script>

<style scoped>
.main-content {
  padding: 10px;
  overflow-y: auto; /* 增加垂直滚动条 */
}

.main {
  margin-top: 10px; /* 主内容与上方内容间隔 */
}

.button-container {
  display: flex; /* 使用flex布局 */
  justify-content: center; /* 水平居中 */
  margin-bottom: 10px; /* 按钮与表格之间的间隔 */
}

</style>
